package com.itc.resource;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.media.Manager;
import javax.microedition.media.Player;

public class SoundManager {
	private static Hashtable mapSound = new Hashtable();
	private static long timeLastSound = 0;
	private static boolean enabled = true;

	static public Player getPlayer(String sound) {
		Player player;
		player = (Player) mapSound.get(sound);
		if (player == null) {
			try {
				String fileSpec = "/";
				fileSpec += sound;
				InputStream is = SoundManager.class
						.getResourceAsStream(fileSpec);
				if (fileSpec.endsWith("mp3"))
					player = Manager.createPlayer(is, "audio/mp3");
				mapSound.put(sound, player);
			} catch (Exception ex) {
			}
		}
		return player;
	}

	public static void playSound(String sound) {
		if (!enabled)
			return;
		if (Math.abs(System.currentTimeMillis() - timeLastSound) < 350) {
			// DebugStuff.print("tried to play 2 sounds too soon");
			return;
		}
		timeLastSound = System.currentTimeMillis();
		Player player = getPlayer(sound);
		try {
			Enumeration enumValues;
			Player playerOther;
			for (enumValues = mapSound.elements(); enumValues.hasMoreElements();) {
				playerOther = (Player) enumValues.nextElement();
				if (playerOther != player
						&& playerOther.getState() == Player.STARTED)
					playerOther.deallocate();
			}
			if (player.getState() == Player.STARTED) {
				// DebugStuff.print("sound already started");
				return;
			}
			player.start();
		} catch (Exception e) {
			// DebugStuff.print(e.toString());
		}
	}

	public static void setEnabled(boolean enabled) {
		SoundManager.enabled = enabled;
	}

}